<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary">添加角色</el-button>
        </el-col>
      </el-row>

      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row class="bdbottom vcenter" :class="{bdtop: index1 === 0}" v-for="(item1, index1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRolesById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二三级权限 -->
              <el-col :span="19">
                <el-row class="vcenter" :class="{bdtop: index2 !== 0}" v-for="(item2, index2) in item1.children" :key="item2.id">
                  <!-- 二级权限 -->
                  <el-col :span="6">
                    <el-tag type="success"  closable @close="removeRolesById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" closable @close="removeRolesById(scope.row,item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label='角色名称' prop="roleName"></el-table-column>
        <el-table-column label='角色描述' prop="roleDesc"></el-table-column>
        <el-table-column label='操作' width="300px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" size="mini" icon="el-icon-edit">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" size="mini" icon="el-icon-delete">删除</el-button>
            <!-- 分配角色按钮 -->
            <el-button type="warning" size="mini" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限的对话框 -->
    <el-dialog title="分配权限" :visible.sync="setRightDialogVisible" width="50%" @close="handleDialogClose">
      <!-- 树形控件 -->
      <el-tree :data="rightslist" ref="tree" :props="treeProps" show-checkbox node-key="id" default-expand-all :default-checked-keys="defkeys"></el-tree>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  prop: [],
  data () {
    return {
      // 所有角色列表数据
      rolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点Id值数组
      defkeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  mounted () {
    this.getRolesList()
  },
  methods: {
    // 获取所有角色的列表
    async getRolesList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      // console.log(res)
    },
    // 根据Id删除对应的权限
    removeRolesById (role, rightId) {
      // 弹框提示用户是否要删除
      // const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '警告', {
      //   confirmButtonText: '确认',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).catch(error => error)
      // if (confirmResult !== 'confirm') {
      //   return this.$message.info('删除已取消')
      // }
      // const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      // if (res.meta.status !== 200) {
      //   return this.$message.error('删除权限失败！')
      // }

      this.$confirm('此操作将永久删除该文件, 是否继续?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        callback: async action => {
          if (action === 'confirm') {
            const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            role.children = res.data
          } else {
            this.$message.info('删除已取消')
          }
        }
      })
      // this.getRolesList()
    },
    // 展示分配权限的对话框
    async showSetRightDialog (role) {
      const { data: res } = await this.$http.get('rights/tree ')
      console.log(res)
      this.roleId = role.id
      this.rightslist = res.data
      // 方法1,通过三次循环
      // this.defkeys = []
      // role.children.forEach(item1 => {
      //   item1.children.forEach(item2 => {
      //     item2.children.forEach(item3 => {
      //       this.defkeys.push(item3.id)
      //     })
      //   })
      // })
      // 递归获取三级节点的Id
      this.getKeys(role, this.defkeys)
      this.setRightDialogVisible = true
    },
    handleDialogClose () {
      this.defkeys = []
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getKeys (right, arr) {
      if (right.children) {
        right.children.forEach(t => {
          this.getKeys(t, arr)
        })
      } else {
        arr.push(right.id)
      }
    },
    async setRights () {
      const keys = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ]
      const rid = keys.join(',')
      console.log(rid)
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: rid })
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败！')
      }

      this.$message.success('分配权限成功！')
      this.setRightDialogVisible = false
      this.getRolesList()
    }
  }
}

</script>

<style lang="less" scoped>
.el-tag{
  margin: 7px;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
